package com.sky.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.domain.Dept;
import com.sky.service.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Api(tags = "部门模块")
@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("/dept")
    public Dept dept(){
        return new Dept();
    }

    @ApiOperation("展示数据")
    @GetMapping("/list")
    public String list( @RequestParam(value = "content",defaultValue = "") String name,
                        Model model,
                        @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<Dept> deptList = deptService.deptList(name);
        PageInfo<Dept> pageInfo = new PageInfo<>(deptList);
        model.addAttribute("pageInfo",pageInfo);
        return "dept/list";
    }

    // 根据id跳转页面 没有id添加页面  ，有id更新页面 然后将数据进行回显
    @ApiOperation("跳转更新页面")
    @GetMapping("/add")
    public String toAddPage(Integer id, Model model,
                            HttpSession session){
        if (id != null){
            Dept dept = deptService.findDeptById(id);
            model.addAttribute("dept",dept);
            session.setAttribute("msg","1");
            return "dept/add";
        }
        session.setAttribute("msg","0");
        return "dept/add";
    }

    // 添加/更新操作
    @ApiOperation("添加/更新操作")
    @PostMapping("/add")
    public String add(Dept dept){
        System.out.println(dept);
        if (dept.getId()!=null){
            deptService.update(dept);
            return "redirect:/dept/list";
        }else{
            deptService.add(dept);
            return "redirect:/dept/list";
        }

    }

    @ApiOperation("删除部门")
    @PostMapping("/delete")
    public String delete(@ApiParam("id") Integer id){
        deptService.delete(id);
        return "redirect:/dept/list";
    }
}
